<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/resource/css/bootstrap-table.min.css" type="text/css">

<!-- Latest compiled and minified JavaScript -->
<script src="/resource/js/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="/resource/js/bootstrap-table-zh-CN.min.js"></script>

<div id="toolbar">
  <div class="btn-group ml-3" role="group" aria-label="Basic example">
      <button type="button" class="btn btn-info "
          onclick="AE()">添加</button>
      <button type="button" class="btn btn-secondary "
          onclick="Frozen()">冻结</button>
      <button type="button" class="btn btn-danger "
      onclick="Del()">删除</button>
  </div>
</div>
<div class="modal fade bd-example-modal-lg" id="AEModal" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="AEModalLongTitle">编辑</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="card-body">
          <form id="AEForm">
            <input type="hidden" name="id" id="aeid"  class="form-control">
            <div class="row">
              <div class="col">
                <div class="position-relative form-group">
                  <label>账号</label>
                  <input name="user_name" placeholder="账号" type="text" class="form-control">
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>密码</label>
                  <input name="password" placeholder="密码为空不修改" type="text" class="form-control">
                </div>
              </div>
            </div>
            <div class="position-relative form-group">
              <label>权限组</label>
              <select name="group_id" class="form-control" id="limit_plan_id">
                <option value="0">无</option>
              </select>
            </div>
            <div class="row">
              <div class="col">
                <div class="position-relative form-group">
                  <label>账号余额<a href="/{{.setting.admin_path}}/recharge_records">（去充值消费添加）</a></label>
                  <input name="balance" placeholder="账号余额" type="number" class="form-control">
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>推广佣金</label>
                  <input name="commission_balance" placeholder="推广佣金" type="number" class="form-control">
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>专享折扣</label>
                  <input name="discount" placeholder="专享折扣" type="number" class="form-control">
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col">
                <div class="position-relative form-group">
                  <label>返利模式</label>
                  <select name="commission_type" class="form-control">
                    <option value="3">跟随系统</option>
                    <option value="1">循环</option>
                    <option value="2">一次性</option>
                  </select>
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>返利比例</label>
                  <input name="commission_rate" placeholder="返利比例" type="number" class="form-control">
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col">
                <div class="position-relative form-group">
                  <label>已用上传流量</label>
                  <input name="u" placeholder="已用上传流量" type="number" class="form-control">
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>已用下载流量</label>
                  <input name="d" placeholder="已用下载流量" type="number" class="form-control">
                </div>
              </div>
            </div>
            
            <div class="position-relative form-group">
              <label>流量</label>
              <input name="transfer_enable" placeholder="流量" type="number" class="form-control">
            </div>
            <div class="position-relative form-group">
              <label>到期时间</label>
              <input name="expired_at" class="form-control" type="datetime-local" value="" >
            </div>

            <div class="row">
              <div class="col">
                <div class="position-relative form-group">
                  <label>是否冻结</label>
                  <select name="banned" class="form-control">
                    <option value="-1">否</option>
                    <option value="1">是</option>
                  </select>
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>是否管理员</label>
                  <select name="is_admin" class="form-control">
                    <option value="-1">否</option>
                    <option value="1">是</option>
                  </select>
                </div>
              </div>
              <div class="col">
                <div class="position-relative form-group">
                  <label>是否员工</label>
                  <select name="is_staff" class="form-control">
                    <option value="-1">否</option>
                    <option value="1">是</option>
                  </select>
                </div>
              </div>
            </div>
            
            <div class="position-relative form-group">
              <label>备注</label>
              <textarea name="remarks" class="form-control" rows="3"></textarea>
            </div>
          </form>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="AEajax()">保存</button>
      </div>
    </div>
  </div>
</div>

<script>

  let planList =  [];

  const $table = $('#table')
  let hasInit = false;
  $(function () {
    initTable()
    getShowPlan()
    for (let index = 0; index < planList.length; index++) {
      const element = planList[index];
      $("#select_group_id").append(`<option value="${element.id}">${element.name}</option>`)
    }
  })

  //获取订阅列表
  function getShowPlan() {
    $.ajax({
        type: "POST",
        async: false,
        url: "/{{.setting.admin_path}}/plan/get_rtm1",
        dataType: "json",

        success: function(data) {
          if (data.code == 0) {
            console.log(data.data)
            for (let index = 0; index < data.data.data.length; index++) {
              const element = data.data.data[index];
              $("#limit_plan_id").append(`<option value="${element.id}">${element.name}</option>`)
              $("#select_group_id").append(`<option value="${element.id}">${element.name}</option>`)
              
            }
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown)
            notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          
        }
    });
  }

  //搜索
  function search() {
    $("#table").bootstrapTable('refresh',{pageNumber:1});
  }
  //清除搜索
  function cleanSearch() {
    $("select[data-function='search']").each(function (i, domEle) {
      // 选择第一个选项
      $(this).val($(this).find('option:first').val());
    })
    $("input[data-function='search']").each(function (i, domEle) {
      $(domEle).val("")
    })
    $("#table").bootstrapTable('refresh');
  }


  //AE表单
  function AE(data) {
    console.log(data)
    $('#AEForm')[0].reset();
    if (data != null) {
        
        $("#AEModalLongTitle").text("编辑")
        $("#AEForm input[type='hidden'],#AEForm input[type='number'],#AEForm input[type='text'],#AEForm input[type='datetime-local'],#AEForm select,#AEForm textarea").each(function (i, v) {

            for (let key in data.user) {
                if (key == $(v).attr("name")) {
                    $(v).val(data.user[key])
                }
            }
        })

        $("#AEForm input[type='checkbox']").each(function (i, v) {
            for (let key in data.user) {
                if (key == $(v).attr("name")) {
                    if (data.user[key] == 1) {
                      $(v).attr("checked","true")
                    }else{
                      $(v).removeAttr("checked")
                    }
                }
            }
        })

        $("#AEForm input[name='password']").val("")

        $("#AEForm input[name='u']").val((data.user.u / 1073741824).toFixed(2))
        $("#AEForm input[name='d']").val((data.user.d / 1073741824).toFixed(2))
        $("#AEForm input[name='transfer_enable']").val((data.user.transfer_enable / 1073741824).toFixed(2))


    } else {
        $("#AEModalLongTitle").text("添加")
        $("#aeid").val("")
        
    }
    $('#AEModal').modal('show')
  }

  //ae提交
  function AEajax() {
    let d = {}
    let t = $("#AEForm").serializeArray();
    $.each(t, function() {
        d[this.name] = this.value;
    });

    $.ajax({
        type: "POST",
        url: "/{{.setting.admin_path}}/user/ae",
        data: d,
        dataType: "json",
        success: function(data) {
            if (data.code == 0) {
              notify('success', "保存成功")
            } else {
              notify('danger', data.message)
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown)
            notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          $('#AEModal').modal('hide')
          $("#table").bootstrapTable('refresh');
        }
    });
  }

  //删除数据
  function Del() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function(v, i) {
      ids.push(v.user.id)
    })

    $.ajax({
        type: "post",
        url: "/{{.setting.admin_path}}/user/del",
        data: {'ids':ids},
        dataType: "json",
        success: function(data) {
          if (data.code == 0) {
            notify('success', "删除成功")
          } else {
            notify('danger', data.message)
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          $("#table").bootstrapTable('refresh');
        }
    });
    
  }

  //冻结数据
  function Frozen() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function(v, i) {
      ids.push(v.user.id)
    })

    $.ajax({
        type: "post",
        url: "/{{.setting.admin_path}}/user/banned1",
        data: {'ids':ids},
        dataType: "json",
        success: function(data) {
          if (data.code == 0) {
            notify('success', "冻结成功")
          } else {
            notify('danger', data.message)
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          $("#table").bootstrapTable('refresh');
        }
    });
    
  }


  //初始化表格
  function initTable() {
    $table.bootstrapTable({
      columns: [
        [
          {

          }, {
            title: '<input type="text"  placeholder="ID" class="form-control" name="id" data-function="search" data-type="like" style="width:60px"/>',
          }, {
            title: '<input type="text"  placeholder="账号" class="form-control" name="user_name" data-function="search" data-type="like" />',
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="banned">
                      <option selected value="0">全部</option>
                      <option value="-1">正常</option>
                      <option value="1">禁用</option>
                    </select>
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="is_admin">
                      <option selected value="0">全部</option>
                      <option value="1">是</option>
                      <option value="-1">否</option>
                    </select>
                  </div>
          `,
          },{
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" name="group_id" id="select_group_id" >
                      <option selected value="0" >全部</option>
                      <option value="-1">未订阅</option>
                    </select>
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="uS" id="select_u" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
                    <input type="text"  placeholder="已用上传流量(GB)" class="form-control" name="u" data-function="search" data-type="size" data-select-binding="#select_u" style="width:80px" />
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="dS" id="select_d" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
                    <input type="text"  placeholder="已经用流量(GB)" class="form-control" name="d" data-function="search" data-type="size" data-select-binding="#select_d" style="width:80px" />
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="transfer_enableS" id="select_transfer_enable" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
          
                    <input type="text"  placeholder="流量(GB)" class="form-control" name="transfer_enable" data-function="search" data-type="size" data-select-binding="#select_transfer_enable" style="width:80px"/>
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select col-4 " name="expired_atS" id="select_expired_at" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
                    <input class="form-control col-8 " type="datetime-local" value="" name="expired_at" data-function="search" data-type="size" data-select-binding="#select_expired_at" >
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="balanceS" id="select_balance" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
          
                    <input type="text"  placeholder="余额" class="form-control" name="balance" data-function="search" data-type="size" data-select-binding="#select_balance" style="width:80px"/>
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="commission_balanceS" id="select_commission_balance" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
          
                    <input type="text"  placeholder="佣金" class="form-control" name="commission_balance" data-function="search" data-type="size" data-select-binding="#select_commission_balance" style="width:80px"/>
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="discountS" id="select_discount" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
          
                    <input type="text"  placeholder="专享折扣" class="form-control" name="discount" data-function="search" data-type="size" data-select-binding="#select_discount" style="width:80px"/>
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="commission_type" data-function="search">
                      <option value="0">全部</option>
                      <option value="3">系统</option>
                      <option value="1">循环</option>
                      <option value="2">一次性</option>
                    </select>
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" name="commission_rateS" id="select_commission_rate" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
          
                    <input type="text"  placeholder="返利比例" class="form-control" name="commission_rate" data-function="search" data-type="size" data-select-binding="#select_commission_rate" style="width:80px"/>
          
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select col-4 " name="created_atS" id="select_created_at" data-function="search">
                      <option selected value="">选择</option>
                      <option value=">=">>=</option>
                      <option value="<="><=</option>
                    </select>
                    <input class="form-control col-8 " type="datetime-local" value="" name="created_at" data-function="search" data-type="size" data-select-binding="#select_created_at" >
          
                  </div>
          `,
          }, {
            title: `

            <div class="input-group">
                    <button type="button" class="btn btn-twitter btn-icon-only" onclick="search()">
                      <span class="btn-inner--icon"><i class="fas fa-search"></i></span>
                    </button>
                    <button type="button" class="btn btn-google-plus btn-icon-only" onclick="cleanSearch()">
                      <span class="btn-inner--icon"><i class="fas fa-trash"></i></span>
                    </button>
                  </div>
          `,
          },
        ], [
          {
            checkbox: true,
          }, {
            field: 'user.id',
            title: 'ID',
            sortable: true, //是否允许排序
            sortName:'id',
          }, {
            field: 'user.user_name',
            title: '账号',
            sortable: true, //是否允许排序
            sortName:'user_name',
          }, {
            field: 'banned',
            title: '账号状态',
            sortable: true, //是否允许排序
            sortName:'banned',
            formatter: function (value, row, index) {
              if (row.user.banned == 1) {
                return `封禁`;
              }else{
                return `正常`;
              }
            }
          }, {
            field: 'is_admin',
            title: '是否管理员',
            sortable: true, //是否允许排序
            sortName:'is_admin',
            formatter: function (value, row, index) {
              if (row.user.is_admin == 1) {
                return `是`;
              }else{
                return `否`;
              }
            }
          },{
            field: 'plan.name',
            title: '订阅',
            sortable: true,
            sortName:'group_id',
          },{
            field: 'u',
            title: '上传流量(GB)',
            sortable: true, //是否允许排序
            sortName:'u',
            formatter: function (value, row, index) {
              return (row.user.u / 1073741824).toFixed(2);
            }
          },{
            field: 'd',
            title: '下载流量(GB)',
            sortable: true, //是否允许排序
            sortName:'d',
            formatter: function (value, row, index) {
              return  (row.user.d / 1073741824).toFixed(2);
            }
          }, {
            field: 'user.transfer_enable',
            title: '流量(GB)',
            sortable: true, //是否允许排序
            sortName:'transfer_enable',
            formatter: function (value, row, index) {
              return (row.user.transfer_enable / 1073741824).toFixed(2) ;
            }
          }, {
            field: 'user.expired_at',
            title: '到期时间',
            sortable: true, //是否允许排序
            sortName:'expired_at',
          }, {
            field: 'user.balance',
            title: '余额',
            sortable: true, //是否允许排序
            sortName:'balance',
          }, {
            field: 'user.commission_balance',
            title: '佣金',
            sortable: true, //是否允许排序
            sortName:'commission_balance',
          }, {
            field: 'user.discount',
            title: '专享折扣',
            sortable: true, //是否允许排序
            sortName:'discount',
          }, {
            field: 'user.commission_type',
            title: 'aff模式',
            sortable: true, //是否允许排序
            sortName:'commission_type',
            formatter: function (value, row, index) {
              let t = "系统错误";
              switch (value) {
                case 1:
                  t = "循环";
                  break;
                case 2:
                  t = "一次性";
                  break;
                case 3:
                  t = "系统";
                  break;
              
                default:
                  break;
              }
              return t;
            }
          }, {
            field: 'user.commission_rate',
            title: '返利比例',
            sortable: true, //是否允许排序
            sortName:'commission_rate',
          }, {
            field: 'user.created_at',
            title: '创建时间',
            sortable: true, //是否允许排序
            sortName:'created_at',
          }, {
            field: 'operate',
            title: '操作',
            width:120,
            events: {
              'click #edit': function (e, value, row, index) {
                AE(row)
              },
              'click #copy_sub': function (e, value, row, index) {
                copy_text("{{.setting.subscribe_domain}}api/subscribe?token=" + row.user.token)
              },
              'click #reset_uuid_token': function (e, value, row, index) {
                reset_uuid_token(row.user.id)
              },
            },
            formatter: function (value, row, index) {
              return `
              <div class="btn-group" role="group" aria-label="Basic example">
                <button id="edit" type="button" class="btn btn-twitter btn-icon-only"><span class="btn-inner--icon"><i class="fas fa-user-edit"></i></span></button>

                <div class="btn-group" role="group">
                  <button type="button" class="btn btn-facebook btn-icon-only" data-toggle="dropdown" aria-expanded="false"> <span class="btn-inner--icon"><i class="fas fa-user-cog"></i></span>
                  </button>

                  <div class="dropdown-menu" style="">
                    <a class="dropdown-item" href="#" id="copy_sub"><i class="far fa-copy"></i>复制订阅</a>
                    <a class="dropdown-item" href="#" id="reset_uuid_token"><i class="fas fa-redo-alt"></i>重置UUID和订阅地址</a>
                  </div>
                </div>

                
                
              </div>`;
              
            }
          }
        ]
      ], //列
      url: '/{{.setting.admin_path}}/user',
      method: 'post', //请求方法
      dataType: 'json',//数据格式
      toolbar: '#toolbar',
      pagination: true, //是否显示页码
      sidePagination: "server",//服务器处理分页
      serverSort: "true",//是否服务器处理排序
      showRefresh: true,  //显示刷新按钮
      showColumns: true, //是否显示列下拉列表按钮
      showFullscreen: true, //是否显示全屏按钮
      responseHandler: function (res) {  //response数据处理

        return {
          "total": res.data.totle,
          "rows": res.data.user_list
        };
      },

      //搜索
      queryParams: function (x) {

        $("select[data-function='search']").each(function (i, domEle) {
          x[$(domEle).attr("name")] = domEle.value
        })

        $("input[data-function='search']").each(function (i, domEle) {
          const bindingDomID = $(domEle).attr("data-select-binding")
          if (bindingDomID != undefined) {
            x[$(bindingDomID).attr("name")] = $(bindingDomID).val()
          }
          x[$(domEle).attr("name")] = domEle.value
        })


        return x
      },
      onColumnSwitch:function(field,checked) { //列选择事件
        window.localStorage.setItem('user_hidden_columns', JSON.stringify($("#table").bootstrapTable('getHiddenColumns').map(function (it) {return it.field})))
        
      },
      onPostBody:function(data){//渲染并在 DOM 中可用后触发
        
        if (hasInit == false &&window.localStorage.getItem('user_hidden_columns') != null) {
          JSON.parse(window.localStorage.getItem('user_hidden_columns')).forEach(v => {
            $("#table").bootstrapTable('hideColumn', v);
          });
        }
        if (!hasInit) hasInit = true
      },

    })
  }

  function copy_text(text) {
      let input_dom = document.createElement('input');
      input_dom.value = text;
      document.body.appendChild(input_dom);//向页面底部追加输入框
      input_dom.select();//选择input元素
      document.execCommand("Copy");//执行复制命令
      notify('success', "复制成功")
      input_dom.remove();//删除动态创建的节点
  }

  function reset_uuid_token(id) {
    $.ajax({
        type: "POST",
        url: "/{{.setting.admin_path}}/user/reset_token_uuid",
        data: {"user_id":id},
        dataType: "json",
        success: function(data) {
            if (data.code == 0) {
              notify('success', "重置成功")
            } else {
              notify('danger', data.message)
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown)
            notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          $("#table").bootstrapTable('refresh');
        }
    });
  }

  document.addEventListener('keyup', function(event) {
    if (event.keyCode === 13) {
        // 回车键按下后的操作
        search()
    }
  });
</script>